package com.pysrc.base.aop;

import com.alibaba.fastjson.JSONArray;
import com.pysrc.base.annotation.LogAnnotation;
import com.pysrc.base.entity.SysLog;
import com.pysrc.base.mapper.SysLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
/**
 * @ClassName:
 * @Auther L.Chen
 * @CreateDate
 * @Description 横切含有LogAnnotation注解修饰的类/方法的日志
 */
@Aspect
@Component
public class LogsAspect {
    @Autowired
    SysLogMapper mapper;
    private void logs(String className, String methodName,Object[] args){
        SysLog log = new SysLog();
        log.setLogClass(className);
        log.setLogMethod(methodName);
        log.setLogArgs(JSONArray.toJSONString(args));
        mapper.insert(log);
    }

    @Around("execution(* com.pysrc.base..*.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object target = point.getTarget();
        MethodSignature signature = (MethodSignature)point.getSignature();
        Method method = signature.getMethod();
        LogAnnotation classAnn = target.getClass().getAnnotation(LogAnnotation.class);
        LogAnnotation methodAnn = method.getAnnotation(LogAnnotation.class);
        if((null!=classAnn&&classAnn.required())||(null!=methodAnn&&methodAnn.required())){
            // 该类上所有方法都有日志切面 or 当前所切方法有日志切面
            logs(target.getClass().getName(),method.getName(),point.getArgs());
        }
        return point.proceed(point.getArgs());
    }
}
